import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation'
import {
    getProductCollectionHtml,
} from './custom_views';

import ErrorView from 'base/views/ErrorView';

const template = require('./templates/ChapterView.mustache');
const ChapterView = Mn.View.extend({
    template: template,
    className: 'taskline-group row quotation_item border_left_block composite content_double_padding',
    regions: {
        'errors': '.errors',
    },
    events: {
        // Items des ouvrages
        'click a[data-action="workitem:edit"]': 'onWorkItemEdit',
    },
    childViewEvents: {
        'action:clicked': "onButtonClicked",
    },
    childViewTriggers: {},
    initialize() {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.user_prefs = Radio.channel('user_preferences');
        this.app = Radio.channel('progressInvoicingApp');
        this.productCollection = this.model.products;
        this.setupEvents();
    },
    setupEvents() {
        this.listenTo(this.productCollection, 'fetched', () => this.render());

        this.listenTo(this.facade, 'bind:validation', () => Validation.bind(this));
        this.listenTo(this.facade, 'unbind:validation', () => Validation.unbind(this));
        this.listenTo(this.model, 'validated:invalid', this.showErrors);
        this.listenTo(this.model, 'validated:valid', this.hideErrors.bind(this));
        this.listenTo(this.productCollection, 'validated:invalid', this.showProductErrors);
    },
    showErrors(model, errors) {
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.$el.removeClass('error');
    },
    showProductErrors(model, errors) {
        this.$el.addClass('error');
        this.showChildView(
            'errors',
            new ErrorView({
                errors: errors
            })
        );
    },
    templateContext() {
        // Collect data sent to the template (model attributes are already transmitted)
        const productHtml = getProductCollectionHtml(this.productCollection)
        return {
            edit: this.getOption('edit'),
            collectionRawHtml: productHtml,
            total_ht: this.user_prefs.request('formatAmount', this.model.get('total_ht'), true)
        };
    },
    onEdit() {
        this.app.trigger('navigate', 'chapters' + '/' + this.model.get('id'));
    },
    /**
     * WorkItem RawHtml Subviews event management
     * 
     */
    /**
     * 
     * @param {Event} event : The onclick event
     * @returns A WorkItemModel instance
     */
    getWorkItemFromEvent(event) {
        const tag = $(event.currentTarget);
        const workId = parseInt(tag.data('workid'));
        const workItemId = parseInt(tag.data('id'));
        const workModel = this.productCollection.get(workId);
        return workModel.items.get(workItemId);
    },
    onWorkItemEdit(event) {
        const model = this.getWorkItemFromEvent(event);
        this.app.trigger('workitem:edit', model);
    },
});
export default ChapterView